from django.shortcuts import render, reverse
from django.http import HttpResponse
import re


class AdminLoginMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    # 是能类的调用方法
    def __call__(self, request):
        # 获取用户request的请求路径
        path = request.path
        # 定义允许访问的路径
        arr = [reverse('myadmin_login'), reverse('myadmin_relogin'), reverse('myadmin_yzm')]

        # 检测用户request的请求路径是否包含/myadmin/，即是否访问后台,
        # 并且如果不在arr列表的页面，都必须带上session token
        if re.match('/myadmin/', path) and path not in arr:
            # 检测是否已经登录
            successuser = request.session.get('successuser', None)
            if not successuser:
                # 没有登录
                return HttpResponse(f'<script>alert("请先登录");location.href="{ arr[0] }"</script>')

        response = self.get_response(request)
        return response

